package com.gzhryc.shared_device.cdcz.core.protocol.v1;

import com.gzhryc.common.StringTools;
import com.gzhryc.shared_device.cdcz.core.protocol.v1.models.BKVData;
import com.gzhryc.shared_device.iot.core.IOTMessage;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * 云端消息
 */
public class V1_CDCZ_IOTCloudMessage extends IOTMessage implements Serializable {

    private String startFlag = "fcff";
    private String endFlag = "fcee";

    private List<BKVData> bkvDataList;

    public V1_CDCZ_IOTCloudMessage() {
        this.bkvDataList = new ArrayList<>();
    }

    public List<BKVData> getBkvDataList() {
        return bkvDataList;
    }

    public void setMessageId(String messageId) {
        super.setMessageId(messageId);
        bkvDataList.add(new BKVData(V1_CDCZConstants.KEY_MSG_ID, messageId));
    }

    public void setCmd(String cmd) {
        super.setCmd(cmd);
        bkvDataList.add(new BKVData(V1_CDCZConstants.KEY_CMD, cmd));
    }

    public void build(){
        byte[] startBytes = StringTools.hexStr2ByteArr(startFlag);
        byte[] endBytes = StringTools.hexStr2ByteArr(endFlag);
        byte[] frameCheckBytes = StringTools.hexStr2ByteArr("f5");

        int total = 2 + this.bkvDataList.size();
        for (BKVData bkvData : this.getBkvDataList()) {
            total = total + bkvData.getDataLength();
        }

        this.bytes = new byte[(total + 5)];
        int num = 0;
        for (int i = 0; i < startBytes.length; i++) {
            this.bytes[num] = startBytes[i];
            num++;
        }
        byte[] lengthBytes = StringTools.hexStr2ByteArr(Integer.toHexString(total));
        if(lengthBytes.length == 2){
            this.bytes[num] = lengthBytes[0];
            num++;
            this.bytes[num] = lengthBytes[1];
            num++;
        }else if(lengthBytes.length == 1){
            this.bytes[num] = 0;
            num++;
            this.bytes[num] = lengthBytes[0];
            num++;
        }
        for (BKVData bkvData : this.getBkvDataList()) {
            byte[] bkvTypes = bkvData.getData();
            for (int i = 0; i < bkvTypes.length; i++) {
                this.bytes[num] = bkvTypes[i];
                num++;
            }
        }
        this.bytes[num] = frameCheckBytes[0];
        num++;
        for (int i = 0; i < endBytes.length; i++) {
            this.bytes[num] = endBytes[i];
            num++;
        }
    }

    @Override
    public byte[] getBytes() {
        if (this.bytes == null) {
            this.build();
        }
        return this.bytes;
    }

    @Override
    public String byte2Hex() {
        if (this.bytes == null) {
            this.build();
        }
        return super.byte2Hex();
    }
}
